/**
 * 
 */
package com.hj.security.service;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.transaction.annotation.Transactional;

import com.hj.dao.AccountManager;
import com.hj.entity.AcctUser;

/**
 * @author huangj 2009-12-4
 */

@Transactional(readOnly = true)
public class UserDetailsServiceImpl implements UserDetailsService {
	@Autowired
	private AccountManager accountManager;

	@Override
	public UserDetails loadUserByUsername(String loginName) throws UsernameNotFoundException, DataAccessException {
		SecurityContextHolder.getContext();
		// 查询用户
		AcctUser user = accountManager.findUserByLoginName(loginName);
		if (user == null)
			throw new UsernameNotFoundException("用户或密码不存在，请重试！");

		// 安全机制用户
		SecurityUser securityUser = new SecurityUser();
		securityUser.setUsername(loginName);
		securityUser.setPassword(user.getPassword());
		securityUser.setGrantedAuths(obtainGrantedAuthorities());
		return securityUser;
	}

	/**
	 * 获得用户所有角色的权限集合.
	 */
	private Collection<GrantedAuthority> obtainGrantedAuthorities() {
		Set<GrantedAuthority> authSet = new HashSet<GrantedAuthority>();
		// for (int i = 0; i < lstRole.size(); i++) {
		// authSet.add(new SimpleGrantedAuthority(lstRole.get(i).getRoleCd()));
		// }
		authSet.add(new SimpleGrantedAuthority("A_USER"));
		return authSet;
	}
}
